import axios from 'axios'
import router from '../router'
import store from '../store'

axios.defaults.baseURL = 'http://123.57.192.191/api'
// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (store.state.token) {
      config.headers.token = store.state.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          localStorage.removeItem('token')
          router.replace({
            path: '/views/login',
            query: { redirect: router.currentRoute.fullPath }
          })
      }
    }
    return Promise.reject(error)
  }
)

export default axios
